const Adminuser = require("../../modules/Adminuser");

module.exports = (app) => {
  const assert = require("http-assert"); /* npm i assert */
  const express = require("express"); /* npm i express@next */
  const jwt = require("jsonwebtoken"); /* npm i jsonwebtoken */

  const router = express.Router({
    mergeParams: true,
  });

  router.post("/", async (req, res) => {
    console.log("123", req);
    if (req.baseUrl === "/admin/api/rest/Item") {
      const model = await req.Model.create(req.body);
      res.send(model);
    } else if (req.baseUrl === "/admin/api/rest/Items") {
      if (req.body.data === "") {
        const model = await req.Model.find({ type: { $in: 1 } });
        res.send(model);
      } else {
        const model = await req.Model.find({
          $and: [
            { type: { $in: 1 } },
            {
              $or: [
                { name: req.body.data },
                { phone: req.body.data },
                { number: req.body.data },
                { carNumber: req.body.data },
              ],
            },
          ],
        });
        res.send(model);
      }
    } else if (req.baseUrl === "/admin/api/rest/ItemList") {
      if (req.body.data === "") {
        const model = await req.Model.find({ type: { $in: 2 } });
        res.send(model);
      } else {
        const model = await req.Model.find({
          $and: [
            { type: { $in: 2 } },
            {
              $or: [
                { name: req.body.data },
                { phone: req.body.data },
                { number: req.body.data },
                { carNumber: req.body.data },
              ],
            },
          ],
        });
        res.send(model);
      }
    }  else if (req.baseUrl === "/admin/api/rest/Hero") {
      if (req.body.data === "") {
        const model = await req.Model.find({ type: { $in: 0 } });
        res.send(model);
      } else {
        const model = await req.Model.find({
          $and: [
            { type: { $in: 0 } },
            { $or: [{ name: req.body.data }, { phone: req.body.data }] },
          ],
        });
        res.send(model);
      }
    } 
    else if (req.baseUrl === "/admin/api/rest/Heros") {
      if (req.body.data === "") {
        const model = await req.Model.find({ type: { $in: 1 } });
        res.send(model);
      } else {
        const model = await req.Model.find({
          $and: [
            { type: { $in: 1 } },
            { $or: [{ name: req.body.data }, { phone: req.body.data }] },
          ],
        });
        res.send(model);
      }
      res.send(model);
    } else if (req.baseUrl === "/admin/api/rest/Heros") {
      if (req.body.data === "") {
        const model = await req.Model.find({ type: { $in: 1 } });
        res.send(model);
      } else {
        const model = await req.Model.find({
          $and: [
            { type: { $in: 1 } },
            { $or: [{ name: req.body.data }, { phone: req.body.data }] },
          ],
        });
        res.send(model);
      }
      res.send(model);
    } else if (req.baseUrl === "/admin/api/rest/NotHero") {
      if (req.body.data === "") {
        const model = await req.Model.find({ type: { $in: 2 } });
        res.send(model);
      } else {
        const model = await req.Model.find({
          $and: [
            { type: { $in: 2 } },
            { $or: [{ name: req.body.data }, { phone: req.body.data }] },
          ],
        });
        res.send(model);
      }
    } else {
      const model = await req.Model.create(req.body);
      res.send(model);
    }
  });

  router.delete("/:id", async (req, res) => {
    await req.Model.findByIdAndDelete(req.params.id, req.body);
    res.send({
      success: true,
    });
  });

  router.get(
    "/",
    async (req, res, next) => {
      const token = String(req.headers.authorization || "")
        .split(" ")
        .pop();
      assert(token, 401, "请先登录");
      const { id } = jwt.verify(token, app.get("secret"));
      assert(id, 401, "请先登录");
      req.user = await Adminuser.findById(id);
      assert(req.user, 401, "请先登录");
      await next();
    },
    async (req, res) => {
      const queryOptions = {};
      if (req.baseUrl === "/admin/api/rest/Item") {
        const model = await req.Model.find({ type: { $in: 0 } })
          .setOptions(queryOptions)
          .limit(100);
        res.send(model);
        return;
      } else if (req.baseUrl === "/admin/api/rest/Hero") {
        const model = await req.Model.find({ type: { $in: 0 } })
          .setOptions(queryOptions)
          .limit(100);
        res.send(model);
        return;
      } else if (req.baseUrl === "/admin/api/rest/Heros") {
        const model = await req.Model.find({ type: { $in: 1 } })
          .setOptions(queryOptions)
          .limit(100);
        res.send(model);
        return;
      } else if (req.baseUrl === "/admin/api/rest/NotHero") {
        const model = await req.Model.find({ type: { $in: 2 } })
          .setOptions(queryOptions)
          .limit(100);
        res.send(model);
        return;
      } else if (req.baseUrl === "/admin/api/rest/Items") {
        const model = await req.Model.find({ type: { $in: 1 } })
          .setOptions(queryOptions)
          .limit(100);
        res.send(model);
        return;
      } else if (req.baseUrl === "/admin/api/rest/ItemList") {
        const model = await req.Model.find({ type: { $in: 2 } })
          .setOptions(queryOptions)
          .limit(100);
        res.send(model);
        return;
      } else {
        const model = await req.Model.find()
          .setOptions(queryOptions)
          .limit(100);
        res.send(model);
        return;
      }
    }
  );

  router.get("/:id", async (req, res) => {
    const model = await req.Model.findById(req.params.id);
    res.send(model);
  });

  router.post("/:id", async (req, res) => {
    const model = await req.Model.findByIdAndUpdate(req.params.id, req.body);
    res.send(model);
  });

  router.put("/:id", async (req, res) => {
    const model = await req.Model.findByIdAndUpdate(req.params.id, req.body);
    res.send(model);
  });

  //   主路由 进行CURD
  app.use(
    "/admin/api/rest/:resource",
    async (req, res, next) => {
      if (req.params.resource === "ItemList") {
        const modelName = "Item";
        req.Model = require(`../../modules/${modelName}`);
      } else if (req.params.resource === "Heros") {
        const modelName = "Hero";
        req.Model = require(`../../modules/${modelName}`);
      } else if (req.params.resource === "NotHero") {
        const modelName = "Hero";
        req.Model = require(`../../modules/${modelName}`);
      } else {
        const modelName = require("inflection").classify(req.params.resource);
        req.Model = require(`../../modules/${modelName}`);
      }
      next();
    },
    router
  );

  const multer = require("multer");
  const upload = multer({
    dest: __dirname + "/../../uploads",
  });
  app.post("/admin/api/upload", upload.single("file"), async (req, res) => {
    const file = req.file;
    file.url = `http://localhost:8070/uploads/${file.filename}`;
    res.send(file);
  });

  app.get("/admin/api/login/:id", async (req, res) => {
    const model = await Adminuser.findById(req.params.id);
    res.send(model);
  });

  // 登陆界面的接口
  app.post("/admin/api/login", async (req, res) => {
    const { username, password } = req.body;
    const admin = require("../../modules/Adminuser");
    const user = await admin.findOne({ username }).select("+password");
    assert(user, 422, "用户不存在");
    /*  if(!user){
        return res.status(422).send({
        message:'用户不存在'
        })
    }
 */
    // 校验密码是否正确
    const istrue = require("bcrypt").compareSync(password, user.password);
    // const istrue = password.compare(password,user.password)
    console.log(istrue);
    assert(istrue, 422, "密码错误");
    /*   if(!istrue){
        return res.status(422).send({
            message:'密码错误'
        })
    } */

    // 返回token
    const id = user._id;
    const token = jwt.sign({ id: user._id }, app.get("secret"));
    res.send({ token, id });
  });

  app.use(async (err, req, res, next) => {
    res.status(err.statusCode || 500).send({
      message: err.message,
    });
  });
};
